import { defineStore } from "pinia";
import { getINfo, login, logout, updatePwd } from "~/api/manager.js";
import { removeToken, setToken } from "~/utils/auth.js";
import { message } from "~/utils/utils.js";

export const useUserCenter = defineStore("userCenter", {
  state: () => {
    return {
      user: {},
      menus: [],
      roleNames: [],
    };
  },
  getters: {},
  actions: {
    login(username, password) {
      return new Promise((resolve, reject) => {
        const form = {
          username: username,
          password: password,
        };
        login(form)
          .then((res) => {
            // 保存token
            setToken(res.token);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    logout() {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            if (res) {
              removeToken();
              message("退出登录成功");
              resolve(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 不请求后端直接退出登录，用于token失效
    logoutWithoutApi() {
      return new Promise((resolve, reject) => {
        removeToken();
        resolve();
      });
    },
    setUserInfo() {
      return new Promise((resolve, reject) => {
        getINfo()
          .then((res) => {
            this.user = res.user;
            this.setMenus(res.menus);
            this.setRoleNames(res.ruleNames);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    UpdatePwd(data) {
      return new Promise((resolve, reject) => {
        updatePwd(data)
          .then((res) => {
            if (res) {
              resolve(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    setMenus(menus) {
      this.menus = menus;
    },
    setRoleNames(ruleNames) {
      this.roleNames = ruleNames;
    },
    setToken(token) {
      setToken(token);
    },
  },
});
